import { UploadService } from './upload.service'
import { Controller, Post, UseInterceptors, UploadedFile, Body, Get, Param, Query } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import * as fs from 'fs'
import * as path from 'path'
import * as multer from 'multer'
import { PUBLIC_PATH, VIDEO_PATH } from '../utils/constant'

// 如果不存在public/uploads目录，则创建uploads文件夹（前提是public文件夹必须存在)
if (!fs.existsSync(PUBLIC_PATH)) {
  fs.mkdirSync(PUBLIC_PATH)
}

// 存储图片路径和名字
const storage = multer.diskStorage({
  // 设置存储路径
  destination: function (req: Request, file, cb) {
    // 根据前端的载体的sort来判断是头像图片还是题目图片，进行分文件摆放
    const sort = (req.body as any).sort

    // 如果不存在这个文件夹则创建
    if (!fs.existsSync(`${PUBLIC_PATH}/${sort}`)) {
      fs.mkdirSync(`${PUBLIC_PATH}/${sort}`)
    }

    cb(null, `${PUBLIC_PATH}/${sort}`)
  },
  // 设置存储的文件名
  filename: function (req, file, cb) {
    // 文件名字
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
    // path.extname返回文件的扩展名
    cb(null, file?.fieldname + '-' + uniqueSuffix + path.extname(file?.originalname))
  }
})

@Controller('upload')
export class UploadController {
  constructor(private readonly ossService: UploadService) {}

  // 图片上传
  @Post('image')
  @UseInterceptors(FileInterceptor('file', { storage }))
  uploadFile(@UploadedFile() files, @Body() body) {
    return this.ossService.uploadImg(files, body.sort)
  }

  // 检查是否存在md5文件
  @Get('check/file')
  checkFileExist(@Query() query) {
    return this.ossService.checkFileExist(query)
  }

  // 分片上传
  @Post('chunk/upload')
  @UseInterceptors(FileInterceptor('chunk'))
  uploadChunk(@UploadedFile() file, @Body() body) {
    return this.ossService.uploadChunk(file, body)
  }

  // 合并分片
  @Get('chunk/merge')
  mergeChunk(@Query() query) {
    return this.ossService.mergeChunk(query)
  }
}